<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="题材名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入题材名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="题材状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:subject:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-sort"
          size="mini"
          @click="toggleExpandAll"
        >展开/折叠</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['system:subject:add']"
        >导入</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="subjectList"
      row-key="subjectId"
      lazy
      :load="load"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      @sort-change="sortTableFun"
    >
      <el-table-column prop="name" label="题材名称" width="260"></el-table-column>
      <el-table-column prop="rate" label="涨幅" width="200"></el-table-column>
      <el-table-column prop="orderNum" label="表单显示排序" width="100"></el-table-column>
      <el-table-column prop="importance" label="热点排序" width="100"></el-table-column>
      <el-table-column prop="mainSort" label="主线排序" width="100"></el-table-column>
      <el-table-column prop="stockCount" label="股票总数" width="100"></el-table-column>
      <el-table-column prop="outline" label="概要" width="100"></el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" sortable="custom" align="center" prop="createTime" width="200">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:subject:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['system:subject:add']"
            v-if="scope.row.level<4"
          >新增</el-button>
          <el-button
            v-if="scope.row.parentId != 0"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:subject:remove']"
          >删除</el-button>
          <el-button
            v-if="scope.row.level >1"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleStockAdd(scope.row)"
            v-hasPermi="['system:stock:add']"
          >新增股票</el-button>
          <el-button
            v-if="scope.row.level >0"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleSubjectPreview(scope.row)"
            v-hasPermi="['system:subject:list']"
          >预览题材</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改题材对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24" v-if="form.parentId !== 0">
            <el-form-item label="上级题材" prop="parentId">
              <treeselect v-model="form.parentId" :options="subjectOptions" :normalizer="normalizer" placeholder="选择上级题材" @select="treeSelected" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="题材名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入题材名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input-number v-model="form.orderNum" controls-position="right" :min="0" placeholder="表格里的排序"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="题材状态">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in dict.type.sys_normal_disable"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
<!--          <el-col :span="12" v-if="form.parentId === 0">-->
          <el-col :span="12">
            <el-form-item label="热点排序" prop="importance">
              <el-input-number v-model="form.importance" controls-position="right" :min="0" placeholder="大于0为‘沸’" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="主线排序" prop="mainSort">
              <el-input-number v-model="form.mainSort" controls-position="right" placeholder="主线题材排序，越大排越前" :min="0"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="概要" prop="outline">
              <el-input v-model="form.outline" type="textarea" placeholder="请输入题材概要" maxlength="512" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="详细介绍">
              <editor v-model="form.detail" :min-height="192"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="添加股票" :visible.sync="stockAddOpen" width="900px">
      <el-form ref="form" :model="stockForm" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-select v-model="stockForm.selectedStockIds" multiple filterable placeholder="请选择">
              <el-option
                v-for="item in selectableStocks"
                :key="item.id"
                :label="item.stockNo+'-'+item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitStockForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="预览题材" :visible.sync="subjectPreviewOpen" width="900px">
      <vue2-org-tree :data="previewData" :horizontal="true"/>
    </el-dialog>
    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
<!--          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
          </div>-->
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSubject, getSubject, delSubject, addSubject, updateSubject, listSubjectExcludeChild,hasChild,updateSubjectStock ,childStockTree} from "@/api/system/subject";
import { selectableStock } from "@/api/system/stock";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import Vue2OrgTree from 'vue2-org-tree'
import 'vue2-org-tree/dist/style.css'
import {getToken} from "@/utils/auth";
export default {
  name: "Subject",
  dicts: ['sys_normal_disable'],
  components: { Treeselect ,Vue2OrgTree},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      previewData: null,
      // 表格树数据
      subjectList: [],
      // 题材树选项
      subjectOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //股票新增弹出框
      stockAddOpen: false,
      subjectPreviewOpen: false,
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 1,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/subject/importData"
      },
      // 查询参数
      queryParams: {
        name: undefined,
        status: undefined,
        parentId: undefined,
      },
      column: undefined,
      order: undefined,
      selectableStocks: [],
      // 表单参数
      form: {},
      stockForm: {
        selectedStockIds: [],
        subjectId: null
      },
      // 表单校验
      rules: {
        parentId: [
          { required: true, message: "上级题材不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "题材名称不能为空", trigger: "blur" }
        ],
        orderNum: [
          { required: true, message: "显示排序不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /**
     * 排序
     * @param column
     */
    sortTableFun(column){//用户点击这一列的上下排序按钮时，触发的函数
      this.column = column.prop.replace(/([A-Z])/g, "_$1").toLowerCase(); //该方法获取到当前列绑定的prop字段名赋值给一个变量，之后这个变量做为入参传给后端
      if (column.prop) { //该列有绑定prop字段走这个分支
        if (column.order === 'ascending') {//当用户点击的是升序按钮，即ascending时
          this.order = 'asc'; //将order这个变量赋值为后端接口文档定义的升序的字段名，之后作为入参传给后端
        } else if (column.order === 'descending') {
          //当用户点击的是升序按钮，即descending时
          this.order = 'desc';//将order这个变量赋值为后端接口文档定义的降序的字段名，之后作为入参传给后端
        }
        this.getList()//且发起后端请求的接口
      }
    },
    /** 查询题材列表 */
    getList() {
      this.loading = true;
      if (this.column){
        this.queryParams.searchValue = this.column + " " + this.order;
      }
      listSubject(this.queryParams).then(response => {
        this.subjectList = this.handleTree(response.data, "subjectId");
        this.loading = false;
      });
    },
    /** 懒加载子节点数据 */
    load(tree, treeNode, resolve) {
      this.queryParams.parentId = tree.subjectId;
      listSubject( this.queryParams ).then(response => {
        const children = this.handleTree(response.data, "subjectId");
        resolve(children);
      });
    },
    /** 转换题材数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.subjectId,
        label: node.name,
        children: node.children
      };
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.stockAddOpen = false;
      this.stockForm = {
        selectedStockIds: [],
        subjectId: null
      };
    },
    // 表单重置
    reset() {
      this.form = {
        subjectId: undefined,
        parentId: undefined,
        ancestors: undefined,
        name: undefined,
        orderNum: undefined,
        outline: undefined,
        detail: undefined,
        level: undefined,
        status: "0",
        rate:undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      if (row != undefined) {
        this.form.parentId = row.subjectId;
      }
      this.open = true;
      this.title = "添加题材";
      listSubject({  status: "0"}).then(response => {
        this.subjectOptions = this.handleTree(response.data, "subjectId");
      });
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      getSubject(row.subjectId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改题材";
        listSubjectExcludeChild(row.subjectId).then(response => {
          this.subjectOptions = this.handleTree(response.data, "subjectId");
          if (this.subjectOptions.length == 0) {
            const noResultsOptions = { subjectId: this.form.parentId, name: this.form.parentName, children: [] };
            this.subjectOptions.push(noResultsOptions);
          }
        });
      });
    },
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      let a = document.createElement('a');
      a.href = '/static/'+'subject_import_template.xlsx';
      //路径中'/'为根目录，即index.html所在的目录
      a.download = name;
      a.click();
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.subjectId != undefined) {
            updateSubject(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSubject(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除名称为"' + row.name + '"的数据项？').then(function() {
        return delSubject(row.subjectId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 处理新增股票 */
    handleStockAdd(row) {
      hasChild(row.subjectId).then(response =>{
        if (response.data == "1") {
          this.$message.error('有子题材不能添加股票');
        }else{
          selectableStock({
            subjectId: row.subjectId
          }).then(response => {
            this.stockForm.selectedStockIds = response.data.selectedStockIds;
            this.stockForm.subjectId = row.subjectId;
            this.selectableStocks = response.data.selectableStocks;
            this.stockAddOpen = true;
          });
        }
      })
    },
    submitStockForm: function() {
      console.log(this.stockForm)
      updateSubjectStock(this.stockForm).then(response => {
        this.$modal.msgSuccess("新增成功");
        this.stockAddOpen = false;
        this.getList();
      });
    },
    /** 处理新增股票 */
    handleSubjectPreview(row) {
      this.previewData = null;
      this.subjectPreviewOpen = true;
      childStockTree(row.subjectId).then(response =>{

        this.previewData = this.transformData(response.data);
        console.log(this.previewData)
      })

    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    transformData(data) {
      if (data === null) {
        return null;
      }
      const transformedData = {};
      for (const key in data) {
        if (key === 'subjectId') {
          transformedData.id = data[key];
        } else if (key === 'name') {
          if (data['stockNo']!=null && data['stockNo']!==undefined){
            transformedData.label = data['stockNo'] + '-' + data[key];
          }else {
            transformedData.label = data[key];
          }
        } else if (key === 'children') {
          if (data.children === null){
            if (data['stocks']!== null){
              transformedData.children = data['stocks'].map(child => this.transformData(child));
            }
          }else {
            transformedData.children = data.children.map(child => this.transformData(child));
          }
        }
      }

      return transformedData;
    }
  }
};
</script>
